<?php
// $Id$
/**
 *@file
 * Create a block with the content of a Google Analytics code
 *
 * ************************
 *       How To Use
 * ************************
 * 
 * Include the file jnj.ga.inc in your module folder
 * Include module_load_include('inc', 'your_module_name', 'jnj.ga');
 * Include init_jnj_ga() in the hook_init()
 * Include menu_jnj_ga($items) in the hook_menu, where $items is the array of menus
 * 
 * 
 */

/**
 * Implementation of hook init
 */
function init_jnj_ga() {
  //include the code int the footer region
  drupal_add_js(_content_jnj_ga(), 'inline', 'footer');
}

/**
 * Implementation of hook_menu
 * create the following pages
 *  - JnJ Google Analytics Settings
 */
function menu_jnj_ga(&$items) {
  //settings menu
  $items['admin/settings/jnj_google_analytics'] = array(
    'title' => t('JnJ Google Analytics settings'),
    'description' => 'Create a block with the Google analitycs code',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('settings_form_jnj_ga'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
}

/**
 * Create the JnJ Google Analytics form settings
 * Its possible to edit:
 *  - Tracker id
 *  - Allowed Urls
 *  - Enabled Log
 */
function settings_form_jnj_ga() {
  $form = Array();
  $form['jnj_ga_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Google Analytics settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );
  $form['jnj_ga_settings']['jnj_ga_tracker'] = array(
    '#type' => 'textfield',
    '#title' => t('Google Analytics Tracker Id'),
    '#default_value' => variable_get('jnj_ga_tracker', 'XX-XXXXXXX-XX'),
    '#required' => TRUE,
    '#description' => 'This is the Tracker Id used by Google'
  );
  $form['jnj_ga_settings']['jnj_ga_url_option'] = array(
    '#type' => 'radios',
    '#title' => t("IP's condition"),
    '#default_value' => variable_get('jnj_ga_url_option', 1),
    '#required' => TRUE,
    '#options' => array('Allow','Disallow'),
    '#description' => 'Select the desired option to allow or disallow this module on the specified IPs bellow'
  );
  $form['jnj_ga_settings']['jnj_ga_allowed_url'] = array(
    '#type' => 'textarea',
    '#cols' => 60,
    '#rows' => 10,
    '#title' => t('IP\'s'),
    '#default_value' => variable_get('jnj_ga_allowed_url', '10.15.150.91'. chr(13) . chr(10) .'10.15.150.92'. chr(13) . chr(10) .'10.15.130.50'. chr(13) . chr(10) .'10.15.130.51'),
    '#required' => TRUE,
    '#wysiwyg' => FALSE,
    '#description' => 'Domains within which this block should be displayed or not, eg. 127.0.0.1 one per line'
  );
  $form['jnj_ga_settings']['jnj_ga_pdf_tracker'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable PDF Tracking'),
    '#default_value' => variable_get('jnj_ga_pdf_tracker', FALSE),
    '#description' => t('Enable PDF tracking on the url pages with .pdf extensions'),
  );
  $form['jnj_ga_settings']['jnj_ga_log'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable log messages'),
    '#default_value' => variable_get('jnj_ga_log', FALSE),
    '#description' => t('Enable log to show if the fake or correct "Tracker ID" is active'),
  );

  $form['jnj_ga_settings']['jnj_ga_settings_exception'] = array(
    '#type' => 'fieldset',
    '#title' => t('Google Analytics settings exception'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );
  $form['jnj_ga_settings']['jnj_ga_settings_exception']['jnj_ga_exception'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable Tracker Exception'),
    '#default_value' => variable_get('jnj_ga_exception', FALSE),
    '#description' => t('Enable Exceptions Tracker'),
  );

  $form['jnj_ga_settings']['jnj_ga_settings_exception']['jnj_ga_tracker_exception'] = array(
    '#type' => 'textarea',
    '#title' => t('GA Tracker Exception. (Path) and GA Tracker Parameter Exception Page'),
    '#default_value' => variable_get('jnj_ga_tracker_exception', ''),
    '#description' => 'This is used by Google in exception pages. Example: user/register|/register/step1',
  );
  return system_settings_form($form);
}

/**
 * exist url track
 */
function exist_jnj_ga_tracker($jnj_path) {
  $track_rows = explode(chr(13),variable_get('jnj_ga_tracker_exception', ''));
  foreach ($track_rows as $track_rows_key => $track_rows_value){
   $track_url       = reset(explode('|',$track_rows_value));
   $track_parameter =  end(explode('|',$track_rows_value));
    if(trim(strtolower($track_url)) == trim(strtolower($jnj_path))){
      return $track_parameter;
    }
  }
  return false;
}

/**
 * Create the content of the google analytics
 */
function _content_jnj_ga() {

  // the variable corresponding to track pdf links
  $jnj_ga_pdf_tracker = variable_get('jnj_ga_pdf_tracker', FALSE);

  $jnj_ga_exception = variable_get('jnj_ga_exception', FALSE);
  $jnj_path = drupal_get_path_alias($_GET['q']);
  
  //tracker default
  $tracker_ga = "_gaq.push(['_trackPageview']);";

  //checks for exception pages
  if($jnj_ga_exception == TRUE){
    $track_parameter = exist_jnj_ga_tracker($jnj_path);
    if($track_parameter != FALSE){
      $tracker_ga = "_gaq.push(['_trackPageview', '" . $track_parameter . "']);";
    }
  }

  // if true, all the urls with pdf extensions will be track.
  if($jnj_ga_pdf_tracker == TRUE){
    $content = "
    $(document).ready(function(){
      $(\"a[href$='.pdf']\").click(function() {
        var url = $(this).attr('href');
        _gaq.push(['_trackPageview', url]);
      });
    });
    ";
  }

  //google analytics default content
  $content .= "
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    " . $tracker_ga . "
    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
  ";

  //check if the actual url is the url of prod site
  //convert the urls in the white list
  $urls = variable_get('jnj_ga_allowed_url', '');
  $white_list = explode(chr(13) . chr(10), $urls);
  $url_option = variable_get('jnj_ga_url_option', 1);
   
  //do a xor comparison to agreee or not...
  //compare with the server ip
  if ( $url_option ^ in_array($_SERVER['SERVER_ADDR'], $white_list)) {
    drupal_add_js(array('sendForGA' => TRUE),'setting');
    //ok, so you can create the block with the correct tracker id
    $content = preg_replace("/_gaq\.push\(\[\'\_setAccount\', \'[^']*\'\]\)\;/",
                            "_gaq.push(['_setAccount', '". variable_get('jnj_ga_tracker', 'XX-XXXXXXX-XX') ."']);",
                            $content);

    $log_message = 'Correct Tracker Id active';
  }
  else {
    $log_message = 'Fake Tracker Id active';
    drupal_add_js(array('sendForGA' => FALSE),'setting');
  }

  //log the messages if enabled
  if (variable_get('jnj_ga_log', FALSE)) {
    watchdog('JnJ - GA', $log_message);
  }

  return $content;
}